//
//  NetworkManager.swift
//  网络请求封装Swift
//
//  Created by apple on 15/10/16.
//  Copyright © 2015年 apple. All rights reserved.
//


import AFNetworking

//enum Method{
//    case GET
//    case POST
//}
/// 相当于typedef 定义一个类型
typealias NetworkCallBack = (resultData:AnyObject?,error:NSError?)->()

class NetworkManager: AFHTTPSessionManager {
   
// MARK:拼接各种URL
    
    /// 授权页面URL(这个是webview加载的主页面)
    /// - see [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oAuthURL:NSURL?{
        
        return NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=642110793&redirect_uri=http://www.baidu.com")
    }

    
// MARK:  单例
    static let sharedManager:NetworkManager = {
        
        let manager = NetworkManager(baseURL: nil)
        
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
//        修改解码器
//        manager.responseSerializer = AFHTTPResponseSerializer()
        return manager
        
        }()
 
}


// MARK:-------请求数据相关
extension NetworkManager
{
    ///发布微博
    func composeStatus(status:String,finished:NetworkCallBack){
        
        let paras = ["status":status]
        
        uploadRequest("https://upload.api.weibo.com/2/statuses/upload.json", parameters: paras, finished: finished)
//        tokenRequest("POST", URLString: "https://api.weibo.com/2/statuses/update.json", parameters: paras, finished: finished)
    }
    
    ///  请求当前登录用户主页的微博
    ///
    ///  - parameter token:    token值
    ///  - parameter since_id:    若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    ///  - parameter max_id:    若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    ///  - parameter finished: 回调,返回数据或错误
    /// - see [http://open.weibo.com/wiki/2/statuses/home_timeline](http://open.weibo.com/wiki/2/statuses/home_timeline)
    func askForStatus(since_id since_id:Int,max_id:Int,finished:NetworkCallBack){
        
        let paras = ["since_id":since_id,"max_id":max_id]
        
        tokenRequest("GET", URLString: "https://api.weibo.com/2/statuses/home_timeline.json", parameters: paras, finished: finished)
    }


    ///  请求获取用户信息的方法
    ///
    ///  - parameter token:    由code获取的token
    ///  - parameter uid:      用户uid
    ///  - parameter finished: 回调,返回数据或错误
    /// - see [http://open.weibo.com/wiki/2/users/show](http://open.weibo.com/wiki/2/users/show)
    func askForUserInfo(uid:String,finished:NetworkCallBack){
        
        let para = ["uid":uid]
        
        tokenRequest("GET", URLString: "https://api.weibo.com/2/users/show.json", parameters: para, finished: finished)
        
    }
    
    
    ///  请求获取token的方法
    ///
    ///  - parameter code:     授权码
    ///  - parameter finished: 回调,返回数据或错误
    /// - see [http://open.weibo.com/wiki/OAuth2/access_token](http://open.weibo.com/wiki/OAuth2/access_token)
    func askForOAuthtoken(code:String, finished:NetworkCallBack){
        //拼接参数
        //key和value都是新浪提供的,可以在文档中查询
        let parameters = ["client_id":"642110793","client_secret":"acac8ea39392e35a1c800725f131db2d","grant_type":"authorization_code","code":code,"redirect_uri":"http://www.baidu.com"]
        //发送请求
        request("POST", URLString: "https://api.weibo.com/oauth2/access_token", parameters: parameters, finished: finished)

    }
}


// MARK:  网络请求
extension NetworkManager
{
    ///拼接参数字典(注意关键字:inout,表示在传值的时候,要传地址,这也说名字在swift中数组,字典不是对象)
    private func para(inout parameters:[String:AnyObject]?){
        //先取到token
        guard let token = UserAccountViewModel.sharedUserAccountViewModel.token else{
            //提示token过期
            print("token过期")
            //            fatalError("init(coder:) has not been implemented")
            //            NSError(domain: "token", code: -1000, userInfo: ["token":"过期"])
            return
        }
        if parameters == nil{
            
            parameters = [String:AnyObject]()
            
            parameters!["access_token"] = token
        }
        
        parameters!["access_token"] = token
    }
    
    ///上传(单张图片加文字)请求方法
    private func uploadRequest(URLString:String,var parameters:[String:AnyObject]?, finished:NetworkCallBack){
        
        para(&parameters)

        /// 请求地址,参数,formData:是要拼接的图片的二进制数据
        POST(URLString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
            
            let data = UIImagePNGRepresentation(UIImage(named: "ad_background")!)
            //name是服务器告诉我们key值,filename一般可以乱写
            formData.appendPartWithFileData(data!, name: "pic", fileName: "sniahi", mimeType: "application/octet-stream")
            }, success: { (_, result) -> Void in
                print(result)
            }) { (_, error) -> Void in
                print(error)
        }
    }

    
//    因为后续的网络方法都需要使用到token值(必须,所以一定有这个参数),所以在封装一个方法,免去token值这一个参数的拼接
    private func tokenRequest(method:String,URLString:String,var parameters:[String:AnyObject]?, finished:NetworkCallBack){
        
        para(&parameters)
        
        //底层还是调用这个方法
        request(method, URLString: URLString, parameters: parameters, finished: finished)
    }
    
    /// 普通请求方法
    private func request(method:String,URLString:String,parameters:AnyObject?, finished:NetworkCallBack){
        
        // 定义了success和failure两个闭包,和GET,POST方法中得闭包类型一样
        let success = {(task:NSURLSessionDataTask, result:AnyObject) -> Void in
//            print("请求数据成功")
            finished(resultData: result, error: nil)
        }
        
        let failure = { (task:NSURLSessionDataTask, error:NSError) -> Void in
//            print("请求数据失败:\(error)")
            finished(resultData: nil, error: error)
        }
        
        
        if method == "GET"{
            GET(URLString, parameters: parameters, success: success, failure: failure)
        }else{
            POST(URLString, parameters: parameters, success: success, failure: failure)
        }
    }
}


